package com.iwe3.operation.service;

import com.iwe3.operation.dto.PermissionDto;
import com.iwe3.operation.entity.UrlPermissionEntity;
import com.iwe3.operation.mapper.UrlPermissionMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UrlPermissionServiceImpl implements IUrlPermissionService {

    private final UrlPermissionMapper urlPermissionMapper;

    public UrlPermissionServiceImpl(UrlPermissionMapper urlPermissionMapper) {
        this.urlPermissionMapper = urlPermissionMapper;
    }

    @Override
    public List<PermissionDto> getPermissionList(Long managerId) {
        // 调用Mapper获取权限列表
        List<UrlPermissionEntity> list = urlPermissionMapper.getPermissionList(managerId);
        // 针对list集合处理，使用 stream流
        return list.stream()
                .filter(e -> e.getParentId() == -1)
                .map(e -> {
                    // 先转换所有的目录【一级菜单】
                    PermissionDto dto = new PermissionDto();
                    dto.setId(e.getId());
                    dto.setName(e.getName());
                    // 再找到对应的二级
                    List<PermissionDto> children = list.stream()
                            .filter(c -> c.getParentId().equals(e.getId()))
                            .map(c -> {
                                PermissionDto child = new PermissionDto();
                                child.setId(c.getId());
                                child.setName(c.getName());
                                child.setUrl(c.getUrl());
                                return child;
                            })
                            .collect(Collectors.toList());
                    dto.setChildren(children);
                    return dto;
                })
                .collect(Collectors.toList());
    }
}
